import numpy as np
import math

# 读取数据
with open("iris.data", "r") as f:
    data = f.read()

# 将数据分割为行并转换为列表
rows = data.split("\n")
data_list = []
for row in rows:
    if row:
        data_row = row.split(",")
        data_list.append(data_row)

# 将数据中的非数字值转换为数字
class_mapping = {"Iris-setosa": 0, "Iris-versicolor": 1, "Iris-virginica": 2}
for i in range(len(data_list)):
    data_list[i][-1] = class_mapping[data_list[i][-1]]

# 将数据转换为numpy数组
data_array = np.array([[float(x) for x in row] for row in data_list])

# 计算均值和方差
mean = [sum(col)/len(col) for col in zip(*data_array)]
std = [math.sqrt(sum((x - m)**2 for x in col) / len(col)) for m, col in zip(mean, zip(*data_array))]

# 计算相关性
corr_matrix = np.zeros((data_array.shape[1]-1, data_array.shape[1]-1))
for i in range(data_array.shape[1]-1):
    for j in range(i+1, data_array.shape[1]-1):
        corr = np.corrcoef(data_array[:,i], data_array[:,j])[0,1]
        corr_matrix[i][j] = corr
        corr_matrix[j][i] = corr
# 制作高斯核
sigma = 1.7
size = 5
x, y = [(i-size) for i in range(size*2+1)], [(i-size) for i in range(size*2+1)]
grid = [(i, j) for i in x for j in y]
gaussian_kernel = [math.exp(-(i**2+j**2)/(2*sigma**2)) for i, j in grid]
gaussian_kernel = [gaussian_kernel[i:i+(size*2+1)] for i in range(0, len(gaussian_kernel), size*2+1)]
total = sum(sum(gaussian_kernel, []))
gaussian_kernel = [[x/total for x in row] for row in gaussian_kernel]

# 打印结果
print("该数据集共有{}个样本，每个样本有{}个特征".format(len(data_list), len(data_list[0])-1))
print("各维度的均值为：\n{}".format(mean))
print("各维度的方差为：\n{}".format(std))
print("各维度之间的相关性为：\n{}".format(np.array(corr_matrix).round(2)))
print("高斯核的sigma为{}，得到的高斯核为：\n{}".format(sigma, np.array(gaussian_kernel).round(2)))